package com.chixing.controller;


import com.chixing.commons.ServerResponse;
import com.chixing.pojo.CustomerTokenDTO;
import com.chixing.pojo.Likes;
import com.chixing.utils.TokenUtil;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author pyc
 * @since 2022-11-07
 */
@Controller
@RequestMapping("/likes")
public class LikesController {

    @Autowired
    private Redisson redisson;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("postlikes")
    @ResponseBody
    public ServerResponse postlikes(String token,Integer evaluationId){
        String keys = "likes::"+evaluationId;
        System.out.println("keys:");
        System.out.println(keys);

        CustomerTokenDTO user = TokenUtil.parseToken(token);
        Integer userId = user.getCustId();

        RLock redissonLock = redisson.getLock(keys+"key");
        redissonLock.lock();

        Long result;

        try {
            if (userId!=null){
                Likes likes = new Likes();
                likes.setLikeStatus(1);
                likes.setLikeTime("2022/09/20 17:50:30");
                likes.setUserId(userId);
                likes.setEvaluationId(evaluationId);
//                result = redisTemplate.opsForSet().add(keys,likes);
                result = redisTemplate.opsForList().rightPush(keys,likes);
            }else
                return ServerResponse.fail("未登录",null);
        }finally {
            redissonLock.unlock();
        }

        return ServerResponse.success("",result);
    }


}
